package chat;



import gui.LoggedIn;

import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import document.DocPermissions;
import document.Document;

import messagepasser.ClockFactory;
import messagepasser.ClockService;
import messagepasser.Message;
import messagepasser.MessagePasser;
import messagepasser.TimeStampedMessage;
import messagepasser.UserInfo;



public class TextChat extends TimerTask {

	
	
	public LoggedIn log;
	UserInfo me=null;
	ClockFactory factory = new ClockFactory();
	ClockService clock = factory.getInstance("Vector");
  //  UserInfo[] users=null;
    List<UserInfo>  usersList =null; 
    String destination;
    Document chatDoc;
    DocPermissions docPerm;
    MessagePasser msgPsr;
    Timer t;
    	   	
    	
	public TextChat(UserInfo me,/*UserInfo[] users,*/LoggedIn log){
		this.log = log;
        this.me=me;
	
	}
	
	public void setDocPasser(Document chatDoc){
		if (t != null) {
			t.cancel();
			t.purge();
		}
		this.chatDoc = chatDoc;
		this.msgPsr = this.chatDoc.getMyPasser();
		t = new Timer();
		t.schedule(this, 1000, 1000);
		
	}
	public Timer getT() {
		return t;
	}

	public void setT(Timer t) {
		this.t = t;
	}

	@Override
	public void run() {

		
		
		Message data1 = chatDoc.getMyPasser().receive();
		if (data1!=null) {
			System.out.println("Message received:" + data1);
			if(data1.getMsgType().equals("TEXT")){
				String tokens[] = data1.getHeader().getSrc().split("@");
				log.jTextArea1.append("\n" + tokens[0] + ":"+data1.getPayload().toString());
			}
		}
		
			
		
	}


	public void sendChatMsg(String destination,String getText) {
		this.destination=destination;
		
		TimeStampedMessage msg = new TimeStampedMessage(destination, me
				.getUsername(), "1000", "1000", getText,false,false);
		msg.setMsgType("TEXT");
		msg.setMulticastMsg(false);
		
	//	System.out.println("textChat send msg is :"+msg.getPayload().toString());
		msg.getHeader().setId(chatDoc.getDocId() + "");
		
		
		this.msgPsr=chatDoc.getMyPasser();
		
	//	System.out.println("textChat send after getMyPasser");
		
		msgPsr.send(msg);
		
	}
}
